package com.ochnas.volunteersignup.service;

import java.util.TimerTask;

import javax.jms.TextMessage;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Node;

/**
 * Task that is invoked periodically to report on 
 * try to register a user with a position if that position is not already filled.
 */
public class NewVolunteerRegistrationTask extends TimerTask {
	private EventWebService eventWebService;

    public static final String NEW_VOLUNTEER_TOPIC = "NewVolunteerQueue";
    private NewVolunteerMessageReceiver newVolunteerMessageListener;
 
    public void run() {
    	Object[] messages = newVolunteerMessageListener.messages.toArray();
    	for (Object o: messages) {
    		if (o instanceof TextMessage) {
    			try {
					String xml = ((TextMessage)o).getText();
					Document doc = DocumentHelper.parseText(xml);
					Node userNode = doc.selectSingleNode("/register/user");
					long userId = Long.parseLong(userNode.valueOf("@id"));
					Node positionNode = doc.selectSingleNode("/register/position");
					long positionId = Long.parseLong(positionNode.valueOf("@id"));
					try {
						
						eventWebService.registerForPositionRPC(positionId, userId);

					} catch (NonUniqueResultException e) {
						// user already volunteered for position
					} catch (NoResultException e) {
						// position is filled
					}
					newVolunteerMessageListener.messages.remove(o);
					
				} catch (Exception e) {
					throw new RuntimeException("Unable to register volunteer for position.", e);
				}
    			
    		}
    	}
    }


	public EventWebService getEventWebService() {
		return eventWebService;
	}


	public void setEventWebService(EventWebService eventWebService) {
		this.eventWebService = eventWebService;
	}


	public NewVolunteerMessageReceiver getNewVolunteerMessageListener() {
		return newVolunteerMessageListener;
	}


	public void setNewVolunteerMessageListener(
			NewVolunteerMessageReceiver newVolunteerMessageListener) {
		this.newVolunteerMessageListener = newVolunteerMessageListener;
	}

}
